package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送短息验证码
     * map集合相当于 pojo类
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成验证码,保存到session里面去
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        log.info(code.toString());
//        session.setAttribute("code",code);
        redisTemplate.opsForValue().set("code_"+phone,code,60, TimeUnit.SECONDS);
        //3.发送验证码
//        SMSUtils.sendMessage("1","1",phone,code);
        return R.success("发送成功");
    }

    /**
     * 用验证码登录
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map,HttpSession session){
        //获取手机号和验证码code
        String phone = map.get("phone");
        String code1 = map.get("code");
        //对比验证码
        // String code2 = (String) session.getAttribute("code");
        String code2 = (String) redisTemplate.opsForValue().get("code_" + phone);
        boolean flag = StringUtils.equals(code1, code2);
        if (!flag){
            return R.error("验证码错误");
        }
        //验证码对比成功之后,判断是否为新用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(phone),"phone",phone);
        User user = userService.getOne(wrapper);
        if (user==null){
            //说明是新用户,保存到数据库
               user =new User();
               user.setPhone(phone);
               user.setStatus(1);
            userService.save(user);
        }
        //登录成功,需要把user里面的信息存入到session中用于过滤器用户登录
        session.setAttribute("user",user.getId());
        //删除redis里面的数据
        redisTemplate.delete("code_"+phone);
        return R.success("登录成功");
    }
}
